package com.harmontronics.hanma.paas.paas.domain.app.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.harmontronics.hanma.paas.paas.common.PageBase;
import com.harmontronics.hanma.paas.paas.consts.NumberEnum;
import com.harmontronics.hanma.paas.paas.domain.app.entity.dictionary.HmDictionary;
import com.harmontronics.hanma.paas.paas.domain.app.entity.valueobject.Fields;
import com.harmontronics.hanma.paas.paas.domain.app.entity.valueobject.I18nKeyEnum;
import com.harmontronics.hanma.paas.paas.domain.app.repository.persistence.HmDictionaryRepository;
import com.harmontronics.hanma.paas.paas.domain.app.repository.po.HmDictionaryPO;
import com.harmontronics.hanma.paas.paas.exception.ErrorKeyException;
import com.harmontronics.hanma.paas.paas.utils.EscapeUtil;
import com.harmontronics.hanma.paas.paas.utils.MyBeanUtils;
import com.harmontronics.hanma.paas.paas.utils.StringUtil;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("hmDictionaryService")
@DS("#header.App-Unique")
public class HmDictionaryService {

    @Autowired
    private HmDictionaryRepository hmDictionaryRepository;

    public HmDictionary findById(Long id) {
        HmDictionaryPO po = hmDictionaryRepository.getById(id);
        return BeanUtil.toBean(po, HmDictionary.class);
    }

    public void save(HmDictionary hmDictionary) {
        // 校验：optionName 和 optionValue 在同一个type下唯一
        validateField(Fields.OPTION_NAME,hmDictionary.getOptionName(),hmDictionary.getType(),null);
        validateField(Fields.OPTION_VALUE,hmDictionary.getOptionValue(),hmDictionary.getType(),null);
        HmDictionaryPO po = MyBeanUtils.transform(hmDictionary, HmDictionaryPO.class);
        hmDictionaryRepository.save(po);
    }

    public void update(HmDictionary hmDictionary) {
        // 校验：修改的选项是否存在
        HmDictionaryPO existPo = hmDictionaryRepository.getById(hmDictionary.getId());
        if(existPo == null){
            throw new ErrorKeyException(I18nKeyEnum.DICTIONARY_OPTION_NOT_EXIST);
        }
        // 校验：optionName 和 optionValue 在同一个type下唯一
        validateField(Fields.OPTION_NAME,hmDictionary.getOptionName(),existPo.getType(),hmDictionary.getId());
        validateField(Fields.OPTION_VALUE,hmDictionary.getOptionValue(),existPo.getType(),hmDictionary.getId());
        MyBeanUtils.copyProperties(hmDictionary,existPo);
        hmDictionaryRepository.updateById(existPo);
    }


    public void remove(List<Long> ids) {
        hmDictionaryRepository.removeByIds(ids);
    }

    public List<HmDictionary> getList() {
        LambdaQueryWrapper<HmDictionaryPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(HmDictionaryPO::getCreateDate);
        List<HmDictionaryPO> pos = hmDictionaryRepository.list(queryWrapper);
        return Convert.toList(HmDictionary.class, pos);
    }

    public PageBase<HmDictionary> getList(int pageNo, int pageSize, String type) {
        Page<HmDictionaryPO> page = new Page<>(pageNo, pageSize);
        /*LambdaQueryWrapper<HmDictionaryPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtil.isNotBlank(type),
                HmDictionaryPO::getType, EscapeUtil.escapeChar(type));
        queryWrapper.orderByAsc(HmDictionaryPO::getCreateDate);*/

        QueryWrapper<HmDictionaryPO> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtil.isNotBlank(type),"type",type);
        queryWrapper.orderByAsc("create_date");
        IPage<HmDictionaryPO> resultPage =
                hmDictionaryRepository.selectPage(queryWrapper, page);
        return PageBase.from(resultPage, HmDictionary.class);
    }


    public void validateField(String key, String value, String type, Long id) {
        LambdaQueryWrapper<HmDictionaryPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HmDictionaryPO::getType, type);
        //更新时，排除自己
        queryWrapper.ne(id != null && id > NumberEnum.ZERO.getNum(), HmDictionaryPO::getId, id);
        if (key.equals(Fields.OPTION_NAME)) {
            queryWrapper.eq(HmDictionaryPO::getOptionName, value);
            if (hmDictionaryRepository.count(queryWrapper) > 0) {
                throw new ErrorKeyException(I18nKeyEnum.DICTIONARY_OPTION_NAME_DUPLICATION);
            }
        } else if (key.equals(Fields.OPTION_VALUE)) {
            queryWrapper.eq(HmDictionaryPO::getOptionValue, value);
            if (hmDictionaryRepository.count(queryWrapper) > 0) {
                throw new ErrorKeyException(I18nKeyEnum.DICTIONARY_OPTION_VALUE_DUPLICATION);
            }
        }
    }

}